<?php

namespace model;

use model\DBConnection;
use \PDO;

class IndexQuery {
	private $params;
	function __construct() {
	}
	public static function registerUser($email, $password, $username) {
		try {
			$conn = DBConnection::getDBConnection ();
			
			$stmt = "INSERT INTO player (email,password,username)
						VALUES (:EMAIL,:PASSWORD,:USERNAME)";
			
			$query = $conn->prepare ( $stmt );
			$query->bindValue ( ":EMAIL", $email, PDO::PARAM_STR );
			$query->bindValue ( ":PASSWORD", md5 ( $password ), PDO::PARAM_STR );
			$query->bindValue ( ":USERNAME", $username, PDO::PARAM_STR );
			$conn->beginTransaction ();
			$query->execute ();
			$conn->commit ();
		} catch ( PDOException $pdoe ) {
			$conn->rollBack ();
			throw new Exception ( "Database error.", $pdoe->getCode () );
		}
	}
	public static function selectUser($email, $password) {
		$conn = DBConnection::getDBConnection ();
		$ret = array ();
		
		$stmt = "SELECT player_id,email,username
			      FROM player 
			      WHERE email = :EMAIL
			      AND password = :PASSWORD";
		$query = $conn->prepare ( $stmt );
		$query->bindValue ( ":EMAIL", $email, PDO::PARAM_STR );
		$query->bindValue(":PASSWORD", md5($password),PDO::PARAM_STR);
		$query->execute();
		 
		$row = $query->fetch();
		$ret['player_id'] = $row['player_id'];
		$ret['username'] = $row['username'];
		 
		if($query->rowCount() != 1){
			return false;
		}
		 
		return $ret;
	}
	public static function userExists($email, $password) {
		$conn = DBConnection::getDBConnection ();
		$stmt = "SELECT email,password
						FROM player
						WHERE email = :EMAIL AND password = :PASSWORD";
		$query = $conn->prepare ( $stmt );
		$query->bindValue ( ":EMAIL", $email, PDO::PARAM_STR );
		$query->bindValue ( ":PASSWORD", md5 ( $password ), PDO::PARAM_STR );
		$query->execute ();
		
		$rows = $query->fetchAll ();
		
		if ($query->rowCount () != 1) {
			return false;
		} else {
			return true;
		}
	}
	public static function emailExists($email) {
		$conn = DBConnection::getDBConnection ();
		$stmt = "SELECT email
						FROM player
						WHERE email = :EMAIL";
		$query = $conn->prepare ( $stmt );
		$query->bindValue ( ":EMAIL", $email, PDO::PARAM_STR );
		$query->execute ();
		
		$rows = $query->fetchAll ();
		
		if ($query->rowCount () != 1) {
			return false;
		} else {
			return true;
		}
	}
	public static function usernameExists($username) {
		$conn = DBConnection::getDBConnection ();
		$stmt = "SELECT username
						FROM player
						WHERE username = :USERNAME";
		$query = $conn->prepare ( $stmt );
		$query->bindValue ( ":USERNAME", $username, PDO::PARAM_STR );
		$query->execute ();
		
		$rows = $query->fetchAll ();
		
		if ($query->rowCount () != 1) {
			return false;
		} else {
			return true;
		}
	}
}